package com.tgpms.web.element.service.impl;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.exception.InsertException;
import com.tgpms.exception.QueryException;
import com.tgpms.exception.UpdateException;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.web.element.dao.WsAcceptDao;
import com.tgpms.web.element.entity.ReceivingReport;
import com.tgpms.web.element.service.ReceivingReportService;

import lombok.extern.slf4j.Slf4j;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
@Slf4j
public class ReceivingReportServiceImpl implements ReceivingReportService {
	
	@Autowired
    private VformInterface vformInterface;
	@Autowired
	private WsAcceptDao wsAcceptDao;

	@SuppressWarnings("unchecked")
	@Override
	public Result addReceivingReportInfo(ReceivingReport en) {
		log.info("实体对象为："+en.toString());
		DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
		DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("HH:mm:ss");
		Result result = new Result();
		//增加D4125屏幕数据
		JSONObject json = new JSONObject();
		json.put("PROJECT", en.getProject());
		json.put("MRR", en.getMrr());
		json.put("PO_NO", en.getPoNo());
		json.put("MRR_STATUS", "O");
		json.put("MRR_DATE", dtf1.format(en.getMrrDate()));
		json.put("RECEIVED_BY", en.getReceivedBy());
		json.put("MRR_NOTES", en.getMrrNotes());
		json.put("MRR_TIME", dateToTimestamp(dtf2.format(en.getMrrDate())));
		json.put("ARRIVAL_STATION", en.getArrivalStation());
		log.info("增加验收单D4125上传参数为："+json.toString());
		Result res1 = vformInterface.insert("D4125", json);
		log.info("增加验收单D4125返回参数为："+res1);
		if (res1 == null || !res1.getSuccess()) {
			throw new InsertException(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
        }
        String resData = res1.getData().toString();
        if (resData.equals("{\"message\":\"login\"}")) {
        	throw new InsertException(ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
        }
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
        	result.setSuccess(false);
			result.setMsg(reJson.get("validateError").toString());
            return result;
        } 
        //更新D4125验收状态
        JSONObject keyjson = new JSONObject();
		keyjson.put("MRR", en.getMrr());
		keyjson.put("PROJECT", en.getProject());
        json.clear();
        json.put("MRR_STATUS", "D");
        Result res2 = vformInterface.update("D4125", keyjson.toString(),json.toString(),null,null,null);
        log.info("修改验收单D4125返回参数为："+res2);
        if (res2 == null || !res2.getSuccess()) {
			throw new UpdateException(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
        }
        resData = res2.getData().toString();
        if (resData.equals("{\"message\":\"login\"}")) {
        	throw new UpdateException(ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
        }
        reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
        	result.setSuccess(false);
			result.setMsg(reJson.get("validateError").toString());
            return result;
        }
        //解析list字符串设备集合
        List<Map<String,Object>> list = JSONArray.parseObject(en.getList(),List.class);
        Map<String, List<Map<String,Object>>> wzmap = new HashMap<String, List<Map<String,Object>>>();
        for (Map<String,Object> m : list) {
            List<Map<String,Object>> tmpList = wzmap.get(m.get("SUPPLIES_CODE").toString());
            if (tmpList == null) {
                tmpList = new ArrayList<>();
                tmpList.add(m);
                wzmap.put(m.get("SUPPLIES_CODE").toString(), tmpList);
            } else {
                tmpList.add(m);
            }
        }
        log.info("集合分组后的结果为："+wzmap);
        String PROJECT = en.getProject();
        String PONO = en.getPoNo();
        String MRR = en.getMrr();
        //循环list，增加D4127,并删除多余D4128设备数据
        for(String s : wzmap.keySet()) {
        	//该物资下的设备集合
        	List<Map<String,Object>> zblist = wzmap.get(s);
        	log.info("该物资下的设备集合为："+zblist);
        	String BOQ = zblist.get(0).get("BOQ").toString();
        	String PSI = zblist.get(0).get("PSI").toString();
        	//查询D4127是否已存在该数据
        	JSONObject keyjson1 = new JSONObject();
        	JSONObject json1 = new JSONObject();
        	keyjson1.put("PROJECT", PROJECT);
        	keyjson1.put("PO_NO", PONO);
        	keyjson1.put("MRR", MRR);
        	keyjson1.put("PO_ITEM", BOQ);
        	keyjson1.put("PSI", PSI);
        	json1.putAll(keyjson1);
        	Result findReslut = vformInterface.find("D4127", json1.toJSONString(), "1", "100", "N", "N", "");
        	log.info("查询物资验收单D4127返回参数为："+findReslut);
            if (findReslut == null || !findReslut.getSuccess()) {
    			throw new QueryException(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            }
            resData = findReslut.getData().toString();
            if (resData.equals("{\"message\":\"login\"}")) {
            	throw new QueryException(ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
            }
            if(resData.equals("[]")) {
            	//增加D4127数据
            	json1.put("WAREHOUSE_LOCATION", en.getArrivalStation());
            	json1.put("CASE_NO", en.getArrivalStation());
            	json1.put("ORIG_PRICE", "0.00");
            	json1.put("MER_QTY", "0");
            	json1.put("MRR_QTY", zblist.size());
            	json1.put("GOODS_SPECIFICATION", "");
            	json1.put("MATERIAL_QUALITY_STATE", "");
            	json1.put("QUALITY_CERTIFICATE_NUMBER", "");
            	json1.put("LOCATION", "");
            	json1.put("MER", "");
            	json1.put("GROUP_NO", "");
            	json1.put("ROSI_NOTE", "");
            	json1.put("USER_DEF", "");
            	json1.put("WEIGHT", "");
            	json1.put("SOURCE", "");
                Result addReslut = vformInterface.insert("D4127", json1);
                log.info("增加物资验收单D4127返回参数为："+addReslut);
                if (addReslut == null || !addReslut.getSuccess()) {
        			throw new InsertException(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
                }
                resData = addReslut.getData().toString();
                if (resData.equals("{\"message\":\"login\"}")) {
                	throw new InsertException(ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
                }
                reJson = JSONObject.parseObject(resData);
                if (reJson.get("status").toString().equals("error")) {
                	result.setSuccess(false);
        			result.setMsg(reJson.get("validateError").toString());
                    return result;
                }
            }
            
            //删除不在此验收集合里的D4128数据
            JSONObject json2 = new JSONObject();
            json2.put("PROJECT=", PROJECT);
            json2.put("PO_NO=", PONO);
            json2.put("MRR=", MRR);
            json2.put("PO_ITEM=", BOQ);
            json2.put("PSI=", PSI);
            json2.put("COMMODITY_NO=", s);
            //查询当前物资下的所有设备
            findReslut = vformInterface.find("D4128", json2.toString(), "1", "1000", "N", "N", "");
            if (findReslut == null || !findReslut.getSuccess()) {
            	throw new QueryException(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            }
            resData = findReslut.getData().toString();
            if (resData.equals("{\"message\":\"login\"}")) {
            	throw new QueryException(ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
            }
            List<Map<String,Object>> alllist = JSONArray.parseObject(resData, List.class);
            List<Map<String,Object>> alllist2 = alllist;
            if(alllist.size()>zblist.size()) {
            	for(int i=0;i<alllist.size();i++) {
                	for(int j=0;j<zblist.size();j++) {
                		if(zblist.get(j).get("EQUIPMENT_CODE").toString()
                				.equals(alllist.get(i).get("EQ_TAG_NO").toString())) {
                			alllist2.remove(i);
                		}
                	}
                }
//            	log.info("alllist2为："+alllist2);
                //封装vform批量删除D4128多余设备信息的集合
                List<Object> alist = new ArrayList<Object>();
                for(Map<String,Object> m : alllist2) {
                	JSONObject a = new JSONObject();
                	a.putAll(keyjson1);
                	a.put("EQ_TAG_NO", m.get("EQ_TAG_NO").toString());
                	alist.add(a);
                }
                JSONArray arr = new JSONArray(alist);
                log.info("封装vform批量删除D4128多余设备信息的集合为："+arr.toString());
                Result delres = vformInterface.deleteBatch("D4128", arr);
                log.info("批量删除D4128返回的信息为："+delres);
            }
            

            for(Map<String,Object> m : zblist) {
            	 //将验收单号更新到验收表
                int i = wsAcceptDao.updateMrrByCode(MRR, m.get("EQUIPMENT_CODE").toString());
                if(i!=1) {
                	result.setSuccess(false);
                	result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
                	return result;
                }
            }
        }
		result.setMsg(ExceptionExplain.SUCCESS_BY_INFOS.getExplain());
        return result;
	}
	
//	private void delete(JSONObject keyjson) {
//		//删除D4125增加的数据
//    	Result delres = vformInterface.delete("D4125", keyjson.toJSONString());
//    	log.info("删除D4125返回的结果为："+delres);
//	}
//	
//	private void delete2(JSONObject keyjson1,JSONObject keyjson) {
//		//删除D4127增加的数据,先把接收数量变成0才能删除
//    	JSONObject upjson = new JSONObject();
//    	upjson.put("MRR_QTY", "0");
//    	Result upres = vformInterface.update("D4127", keyjson1.toString(),
//    			upjson.toString(), null, null, null);
//    	log.info("修改D4127返回的结果为："+upres);
//    	Result delres = vformInterface.delete("D4127", keyjson1.toJSONString());
//    	log.info("删除D4127返回的结果为："+delres);
//		//删除D4125增加的数据
//    	delres = vformInterface.delete("D4125", keyjson.toJSONString());
//    	log.info("删除D4125返回的结果为："+delres);
//	}

	
	private long dateToTimestamp(String time) {
        int hh = Integer.parseInt(time.substring(0, 2));
        int mi = Integer.parseInt(time.substring(3, 5));
        int ss = Integer.parseInt(time.substring(6));
        long ts = (hh * 60 * 60) + (mi * 60) + ss;
        return ts;
    }
}
